﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
using MyCalManager.Data;



namespace MyCalManager.Helper
{
    public class ListViewFilterExtension
    {
        /// <summary>
        /// FilterSource Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty FilterSourceProperty =
            DependencyProperty.RegisterAttached("FilterSource",
            typeof(InfoTextBox), typeof(ListViewFilterExtension),
                new FrameworkPropertyMetadata(null,
                    new PropertyChangedCallback(OnTextBoxSet)));


        /// <summary>
        /// Gets the FilterSource property.  
        /// </summary>
        public static InfoTextBox GetFilterSource(DependencyObject d)
        {
            return (InfoTextBox)d.GetValue(FilterSourceProperty);
        }

        /// <summary>
        /// Sets the FilterSource property.  
        /// </summary>
        public static void SetFilterSource(DependencyObject d, InfoTextBox value)
        {
            d.SetValue(FilterSourceProperty, value);
        }

        /// <summary>
        /// Handles changes to the FilterSource property.
        /// </summary>
        private static void OnTextBoxSet(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            ListView listView = d as ListView;
            InfoTextBox textBox = e.NewValue as InfoTextBox;

            if ((listView != null) && (textBox != null))
            {
                textBox.TextChanged += delegate(object sender, TextChangedEventArgs tcea)
                {
                    ICollectionView view =
                        CollectionViewSource.GetDefaultView(listView.ItemsSource);
                    view.Filter = null;
                    view.Filter = delegate(object obj)
                    {
                        Foodstuff filterableObject = obj as Foodstuff;
                        if (filterableObject == null) return false;

                        string textFilter = ((InfoTextBox)sender).Text;

                        if (textFilter.Trim().Length == 0) return true; // the filter is empty - pass all items

                        return filterableObject.Item.Contains(textFilter.Trim());
                    };
                };
            }
        }
    }

}
